package com.wf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.constant.RedisConstant;
import com.wf.context.BaseContext;
import com.wf.domain.MyFavorites;
import com.wf.dto.PageDTO;
import com.wf.service.MyFavoritesService;
import com.wf.service.impl.MyFavoritesServiceImpl;
import com.wf.utils.RedisUtil;
import com.wf.vo.HouseDetailsPageVO;
import com.wf.vo.PageResultVO;
import com.wf.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 我的收藏
 *
 * @author mpk
 * @since 2024/8/28 19:56:14
 */
@RestController
@CrossOrigin
@RequestMapping("/app/myfavorites")
public class MyFavoritesController {


    @Autowired
    MyFavoritesService myFavoritesService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * @param contractId
     */

    @PostMapping("/{contractId}")
    public Result insertMyFavorites(@PathVariable Integer contractId) {
        LambdaQueryWrapper<MyFavorites> wrapper = new LambdaQueryWrapper<MyFavorites>()
                .eq(MyFavorites::getContractId, contractId)
                .eq(MyFavorites::getUserId, BaseContext.getCurrentId());
        MyFavorites favorites = myFavoritesService.getOne(wrapper);
        if (favorites != null) {
            return Result.failure("请勿重复收藏！");
        } else {
            favorites = new MyFavorites();
            favorites.setContractId(contractId);
            favorites.setUserId(BaseContext.getCurrentId());
            myFavoritesService.save(favorites);
        }
        if(redisUtil.hasKey(RedisConstant.APARTMENT_HOUSE_FAVORITE_COUNT + BaseContext.getCurrentId()))
        {
            redisUtil.incr(RedisConstant.APARTMENT_HOUSE_FAVORITE_COUNT + contractId,1L);
        }else
        {
            redisUtil.set(RedisConstant.APARTMENT_HOUSE_FAVORITE_COUNT + contractId,1L);
        }

        return Result.success("收藏成功！");

    }

    @DeleteMapping("/{contractId}")
    public Result deleteMyFavorites(@PathVariable String contractId) {

        LambdaQueryWrapper<MyFavorites> wrapper = new LambdaQueryWrapper<MyFavorites>()
                .eq(MyFavorites::getContractId, contractId)
                .eq(MyFavorites::getUserId, BaseContext.getCurrentId());

        boolean b = myFavoritesService.remove(wrapper);

        if (b) {
            redisUtil.decr(RedisConstant.APARTMENT_HOUSE_FAVORITE_COUNT + contractId,1L);
            return Result.success("取消收藏成功");
        } else {
            return Result.failure("取消收藏失败");
        }

    }

    /**
     * 我的收藏页面
     * @param pageDTO
     * @return
     */
    @PostMapping("/page")
    public Result getMyFavorites(@RequestBody PageDTO pageDTO) {

        PageResultVO<HouseDetailsPageVO> housePageVO = myFavoritesService.getList(pageDTO);

        return Result.success(housePageVO);

    }


}
